<template>
  <view class="yh-page">
	<view class="page">
		<view class="uni-column">
			<view class="yh-title">先执行登录,在登录状态下,测试微信支付</view>
			<view class="yh-title">为了调试方便,开发环境下,可以直接用用户id登录</view>
		</view>
		<view class="uni-form-item uni-column">
			<view class="title"><text class="red">*</text>用户id</view>
			<view class="uni-input-wrapper">
				<input class="uni-input" name="user_id" v-model="user_id" placeholder="请输入用户id"  @input="inputClearUserIdInput" />
				<text class="uni-icon" v-if="showClearUserIdIcon" @tap="handleToClearUserIdIcon">&#xe434;</text>
			</view>
			<button type="primary" @tap="handleToLoginByUserId()">执行登录</button>
		</view>
		<br/>
		<view class="uni-column">
			<view class="yh-title">测试微信支付</view>
		</view>
		<view class="uni-form-item uni-column">
			<view class="title"><text class="red">*</text>测试订单id(不填写为1)</view>
			<view class="uni-input-wrapper">
				<input class="uni-input"  v-model="payForm.order_id" placeholder="请输入订单id"  @input="inputClearInput(0)" />
				<text class="uni-icon" v-if="showClearIconArray[0]" @tap="handleToClearIcon(0)">&#xe434;</text>
			</view>
		</view>
		<view class="uni-form-item uni-column">
			<view class="title"><text class="red">*</text>测试支付金额(不填写为1元)</view>
			<view class="uni-input-wrapper">
				<input class="uni-input"  v-model="payForm.real_pay_amount" placeholder="请输入测试支付金额,默认单位(元)"  @input="inputClearInput(1)" />
				<text class="uni-icon" v-if="showClearIconArray[1]" @tap="handleToClearIcon(1)">&#xe434;</text>
			</view>
		</view>
		<button type="primary" @tap="handleToTestPayOrder()">发起支付</button>
	</view>
  </view>
</template>
<script>
import { loginByUserId }  from '@/api/test/login/wechat-login.js'
import { testPayOrder } from '@/api/test/pay/pay'
import { validNumber } from '@/utils/validate'
import { isWechat } from '@/utils/wechat'	
import store from '@/store';

function onBridgeReady(data)
{
  WeixinJSBridge.invoke('getBrandWCPayRequest', 
  {
	  "appId": data.appId,  //"wx2421b1c4370ecxxx",   //公众号ID，由商户传入    
	  "timeStamp":data.timeStamp,//"1395712654",   //时间戳，自1970年以来的秒数    
	  "nonceStr": data.nonceStr, //"e61463f8efa94090b1f366cccfbbb444",      //随机串    
	  "package":"prepay_id="+data.prepay_id, //"prepay_id=wx21201855730335ac86f8c43d1889123400",
	  "signType": "RSA",     //微信签名方式：    
	  "paySign": data.paySign//"oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ\/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\/xDg==" //微信签名
  },
  function(res) 
  {
	  if (res.err_msg == "get_brand_wcpay_request:ok") 
	  {
		  // 使用以上方式判断前端返回,微信团队郑重提示：
		  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
		  uni.showToast({
			image: "/static/test/notice/01-success.png",
			title: "支付成功",
			mask:true,
			duration:2000
		  })
		  
		  uni.navigateTo({
			url:'/pages/Test/V1/tabBar/index/index'
		  })
	  }
  });
}
if (typeof WeixinJSBridge == "undefined") 
{
  if (document.addEventListener) 
  {
	  
	  document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
  } 
  else if (document.attachEvent) 
  {
	  document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
	  document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
  }
} 
export default 
{
  //计算属性
  computed:
  {

  },
  //监听
  watch:
  {

  },
  data() 
  {
    return{
		//是否在微信环境下
		isWechat:false,
		user_id:null,
		//控制是否显示清除user_id的图标
		showClearUserIdIcon:false,
		payForm:{
			order_id:null,
			real_pay_amount:null,
			pay_type:10
		},
		//控制是否显示清除按钮
		showClearIconArray:[false,false,false,false],
    };
  },
  //页面加载
  onLoad() 
  {
	this.isWechat = isWechat()
  },
  //页面显示
  onShow() 
  {

  },
  //页面初次渲染完成
  onReady()
  {

  },
  //页面隐藏
  onHide()
  {

  },
  //页面卸载
  onUnload()
  {

  },
  methods:
  {
	//监听是否清除用户图标
	inputClearUserIdInput()
	{
	    if (this.user_id.length > 0) 
		{
	        this.showClearUserIdIcon = true;
	    } 
		else 
		{
	        this.showClearUserIdIcon = false;
	    }
	},
	//点击清除用户id
	handleToClearUserIdIcon() 
	{
	    this.inputUserId = null;
		this.user_id = null;
	    this.showClearUserIdIcon = false;
	},
	//用户id登录
	async handleToLoginByUserId()
	{
		let validatedNumber =  validNumber(this.user_id)
		
		if(!validatedNumber)
		{
			uni.showToast({
				image: "/static/test/notice/04-error.png",
				title: "必须是数字",
				mask:true,
				duration:2000
			})
			
			return 
		}
		
		let _this = this
		let param = {}
		param['user_id'] = this.user_id
		const result = await loginByUserId(param).then(res=>
		{
			return new Promise((resolve,reject)=>{
				if(res && res.code == 0)
				{
					
					resolve(res.data)
				}
			})
		})
		const {token,openid} = result
		
		if(token)
		{
			_this.$store.dispatch('user/loginSaveToken',token)
			
			if(openid)
			{
				_this.$store.dispatch('user/authSaveOpenid',openid)
			}
		}
		
	},
	//监听输入事件
	inputClearInput(index)
	{
		//跟表单做一个映射
		let nameArray = ['order_id','real_pay_amount']
		
		if(this.payForm[nameArray[index]].length > 0)
		{
			this.showClearIconArray[index] = true
		}
		else
		{
			this.showClearIconArray[index] = false
		}
		
	},
	//点击清空图标
	handleToClearIcon(index)
	{
		//跟表单做一个映射
		let nameArray = ['order_id','real_pay_amount']
		
		this.payForm[nameArray[index]] = null
		this.showClearIconArray[index] = false
	},
	//发起支付测试
	handleToTestPayOrder()
	{
		console.log(this.user_id)
		
		if(this.user_id)
		{
			
			testPayOrder(this.payForm).then(res =>{
				console.log(res)
				if(res && res.code ===0)
				{
					onBridgeReady(res.data)
				}
			})
			
		}
	}
  }

}
</script>

<style lang="scss" scoped>
.page{
	width:calc(100% - 70rpx);
	padding:35rpx;
}
.title {
        padding: 5rpx 13rpx;
    }

.uni-input-wrapper {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	flex-wrap: nowrap;
	background-color: #FFFFFF;
}

.uni-input {
	height: 80rpx;
	line-height: 80rpx;
	font-size: 36rpx;
	padding: 0rpx;
	flex: 1;
	background-color: #FFFFFF;
}

.uni-icon {
	font-family: uniicons;
	font-size: 80rpx;
	font-weight: normal;
	font-style: normal;
	width: 80rpx;
	height: 80rpx;
	line-height: 80rpx;
	color: #999999;
}

.uni-eye-active {
	color: #007AFF;
}

.red{
	color:red;
	font-weight: true;
}
</style>
